package com.braingina.keyboarddock;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class DockBroadcastReciever extends BroadcastReceiver {

	private final static String DOCK_STATE_LABEL = "android.intent.extra.DOCK_STATE";
	private BluetoothAdapter adapter;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		setAdapter();
		Boolean isDocked = getDockState(intent);
		handleKeyboardDockAction(isDocked);
		showMessage(context, isDocked);
	}
	
	
	private void setAdapter() {
		this.adapter = BluetoothAdapter.getDefaultAdapter();
	}
	
	private Boolean hasBluetooth() {
		return this.adapter != null;
	}
	
	private Boolean bluetoothEnabled() {
		if (hasBluetooth()) {
			final int state = adapter.getState();
			return (state == BluetoothAdapter.STATE_ON || 
					state == BluetoothAdapter.STATE_TURNING_ON);
		}
		
		return false;
	}
	
	private void handleKeyboardDockAction(Boolean isDocked) {
		if (!isDocked && bluetoothEnabled()) {
			this.adapter.disable();
		}
		else if (isDocked && hasBluetooth() && !bluetoothEnabled()) {
			this.adapter.enable();
		}
	}
	
	private static Boolean getDockState(Intent intent) {
		Bundle extras = intent.getExtras();
		Boolean docked = (extras.getInt(DOCK_STATE_LABEL) != Intent.EXTRA_DOCK_STATE_UNDOCKED);
		
		return docked;
	}
	
	private void showMessage(Context context, Boolean isDocked) {
		
		String dockMessage = isDocked ? "Docked" : "Undocked";
		String btMessage = bluetoothEnabled() ? "Bluetooth ON" : "Bluetooth OFF or Unavailable";
		String message = dockMessage + ". " + btMessage + ".";
		
		Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
		toast.show();
	}
}
